package com.youzan.cloud.component.biz.member.common.util;
import com.youzan.cloud.component.biz.member.service.impl.AbstractService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@Component
public class BeanUtil implements ApplicationContextAware {


    private static ApplicationContext applicationContext;

    /**
     * 获取applicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }


    public static  <T extends AbstractService> T getService(Class<T> clazz){
        ApplicationContext context = getApplicationContext();
        T service =  context.getBean(clazz);
        return service;
    }

    public static <T> T getServiceByInterface(Class<T> clazz){
        Map<String, T> result = getApplicationContext().getBeansOfType(clazz);
        return CollectionUtils.isEmpty(result)? null : result.values().iterator().next();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(BeanUtil.applicationContext == null) {
            BeanUtil.applicationContext = applicationContext;
        }
    }

    /**
     * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        if (name == null || applicationContext == null)
            return null;
        return (T) applicationContext.getBean(name);
    }

}
